package cn.chinaunicom.admin.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import cn.chinaunicom.fast.common.params.CorsParams;

/**
 * @ProjectName: cloud
 * @Package: com.springboot.cloud.gateway.config
 * @ClassName: CorsConfig
 * @Description: 跨域配置
 * @Author: wangjc
 * @CreateDate: 2020/3/20 0020 16:11
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/3/20 0020 16:11
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
@Configuration
public class CrossConfig {
    @Autowired
    private CorsParams corsParams;

    @Bean
    public CorsFilter corsFilter() {
        org.springframework.web.cors.UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        return new CorsFilter(source);
    }

    private CorsConfiguration corsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        /*
         * 请求常用的三种配置，*代表允许所有，当时你也可以自定义属性（比如header只能带什么，只能是post方式等等）
         */
        corsConfiguration.addAllowedOriginPattern(corsParams.getAllowedOrigin());
        corsConfiguration.addAllowedHeader(corsParams.getAllowedHeader());
        corsConfiguration.addAllowedMethod(corsParams.getAllowedMethod());
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }
}
